<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--    <link href="../window/css/window.css" rel="stylesheet" />-->
<!--    <link href="../window/css/print.css" rel="stylesheet" />-->
<!--    <link href="../source/css/base.css" rel="stylesheet" />-->
<!--    <link href="../source/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />-->
<!--    <link href="../source/css/bootstrap-select.min.css" rel="stylesheet" />-->
<!--    <link href="../window/css/livecoverage_win.css" rel="stylesheet" />-->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>批量报到</title>
    <link rel="stylesheet" href="../source/layui-v2.5.6/css/layui.css">
    <link href="../source/css/primary.css" rel="stylesheet"/>
    <link href="../window/css/livecoverage_win.css" rel="stylesheet" />
    <script src="../source/jquery/dist/jquery.js"></script>
    <script src="../source/layer/layer.js"></script>
    <script src="../source/js/jquery.qrcode.min.js"></script>
    <script src="../source/js/JsBarcode.all.min.js"></script>
    <script src="../source/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="../source/js/bootstrap-select.min.js"></script>
    <script src="../source/js/common_url.js"></script>
    <script src="../source/js/util.js"></script>
    <script src="../window/js/livecoverage_win.js"></script>
    <style>
        #table_batch{
            height: 580px;
            position: relative;
            overflow-y: auto;
        }
        th,td{
            border: 1px solid #0f0f0f;
            text-align: center;
            height: 34px;
            line-height: 34px;
        }
        .fancyTable{
            margin: 0 auto 30px;
        }
        .btnDel{
            background-color: #FC5E5D;
            width: 66px;
            height: 28px;
            line-height: 26px;
            border-radius: 3px;
            border: none;
            color: white;
        }

        .batch-footer {
            position: fixed;
            bottom: 13px;
            left: 0;
            right: 0;
            text-align: center;
        }

        .but_ok {
            height: 30px;
            line-height: 30px;
        }

        .layui-table th {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="theme-blue">
    <div id="table_batch">
        <table class="layui-table" id="t_table_batch">
            <thead>
            <tr>
                <th width="6%" class="number">序号</th>
                <th width="16%" class="number">患者ID</th>
                <th width="16%" class="nameStyle">患者姓名</th>
                <th width="16%">挂号科室</th>
                <th width="14%">操作</th>
            </tr>
            </thead>
            <tbody id="t_table_plbd_content"></tbody>
        </table>
    </div>
    <div class="batch-footer">
        <button type="button" class="layui-btn" id="batchBtn">批量报到</button>
        <button type="button" class="layui-btn layui-btn-primary" id="batchExit">关闭</button>
    </div>
</div>
<div id="print" style="display: none;width: 70mm; height: 70mm;">
    <table>
        <tr style="height: 6mm">
            <td colspan="2" style="text-align: center">
                <h2 style="font-family:'SimSun'; font-weight:900; margin-top: 0px;
    margin-bottom: 5px;"><span id="hospitalName"></span>报到凭证</h2>
            </td>
        </tr>
        <tr>
            <td colspan="2"
                style="width: 100%; height: 0; border: 0; border-top: 1px solid #000; line-height: 0;margin-bottom: 2px;">
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center" valign="middle" style="width: 100%; height: 5mm">
                <img id="lineCode" width="300px" height="40px" align="center" src="lineCodeTag"/>
            </td>
        </tr>
        <tr style="height: 5mm">
            <td style="width: 40%; text-align: right; font-size:20px; font-weight:900;">就诊号:</td>
            <td style="text-align: left; font-weight:700; font-size:20px;"><label id="registerId"/></td>
        </tr>
        <!--<tr style="height: 7mm">
              <td style="width: 40%; text-align: right; font-size:20px; font-weight:900;">患者ID:</td>
              <td style="text-align: left; font-size:20px;"><label id="patientId" /></td>
          </tr>-->
        <tr style="height: 5mm">
            <td style="width: 40%; text-align: right; font-size:20px; font-weight:900;">患者姓名:</td>
            <td style="text-align: left; font-size:20px;"><label id="patientName"/></td>
        </tr>
        <tr style="height: 5mm">
            <td style="width: 40%; text-align: right; font-size:20px; font-weight:900;">挂号科室:</td>
            <td style="text-align: left; font-size:20px;"><label id="deptName"/></td>
        </tr>
        <tr style="height: 5mm">
            <td style="width: 40%; text-align: right; font-size:20px; font-weight:900;">号别:</td>
            <td style="text-align: left; font-size:20px;"><label id="numType"/></td>
        </tr>
        <!--<tr style="height: 7mm">
              <td style="width: 40%; text-align: right; font-size:20px; font-weight:900;">午别:</td>
              <td style="text-align: left; font-size:20px;"><label id="wuBie" /></td>
          </tr>-->
        <tr style="height: 5mm">
            <td style="width: 40%; text-align: right; font-size:20px; font-weight:900;">挂号时间:</td>
            <td style="text-align: left; font-size:20px;"><label id="registerTime"/></td>
        </tr>
        <tr style="height: 5mm">
            <td style="width: 40%; text-align: right; font-size:20px; font-weight:900;">报到时间:</td>
            <td style="text-align: left; font-size:20px;"><label id="arrivalTime"/></td>
        </tr>
        <tr>
            <td colspan="2"
                style="width: 100%; height: 0; border: 0; border-top: 1px solid #000;line-height: 0;margin-bottom: 2px;"></td>
        </tr>
        <tr>
            <td colspan="2" style="width: 100%; text-align: left; font-size:22px; font-weight:900;">
                您前面还有<label id="prePatientNum"></label>人，请在候诊区耐心等待叫号！
            </td>
        </tr>
        <!--<tr>
              <td colspan="2" align="center" valign="middle" id="imgCode"><img id="imgCodeId" src="imgCodeTag" /></td>
          </tr>-->
    </table>
</div>
<script>
    var res = {
        "status": 0,
        "desc": "手动报到成功",
        "data": [{
            "deptName": "东区心电图室",
            "systemId": "0634b4922c844e288e6613976ba404dadev",
            "queueInfo": [{
                "pretestStage": "0",
                "queueId": "ca548eb1d10c475a81799372f1d91641",
                "patientName": "测试A2",
                "showName": "",
                "wuBie": "0",
                "registerTime": "2023-01-10 10:11:59",
                "bookSignInStatus": "1",
                "isTriage": "0",
                "registerObjName": "东区心电图普通队列",
                "isSign": "0",
                "doctorName": "",
                "queueName": "东区心电图普通队列",
                "registerObjKey": "a6852258dde64ef39e8bc46793416503_1",
                "patientKey": "9532494d",
                "id": "0b1e01bf268c42a09c32c9e77b8d67f1"
            }],
            "systemName": "东区心电图室分诊叫号子系统",
            "deptId": "a6852258dde64ef39e8bc46793416503"
        }]
    };
    var ajaxPrintTicket = STSUrl + "/sign/printOutTicketNew";
    $(function () {
        // dealResData(res.data,'9532494d')
        $('#batchExit').on('click',function () {
            parent.$('#d_right_content iframe')[0].contentWindow.coloseBatchChecks();
        })
    });
    //刷卡报到
    var queryPatientKeyUrlUrl = STSUrl + "/sign/initSignCardKey";//刷卡报到
    var fstBdUrl = STSUrl + "/sign/firstSign";//出诊报到
    var manualTriageUrl = STSUrl + "/sign/manualTriage";//手动分诊
    //分诊台ID
    var _triageId = getDeviceId();
    var countList = 1;
    var _queueInfoArr = [];
    var patientKeyArr = [];
    var _patientKeyArr = [];//重复报到时提示就诊号
    //c端传就诊卡号后报到(c端在index页面调用方法，最后传值到本页面）
    function passCardToBatch(patientKey) {
        if ((patientKey == null) || (patientKey == undefined) || (patientKey == '')) {
            return layer.msg('请输入患者id!');
        }

        $.ajax({
            url: queryPatientKeyUrlUrl,
            type: 'post',
            data: {
                triageId: _triageId, //患者就诊号
                patientCardKey: patientKey//物理卡号
            },
            success: function (d) {
                var dataInfo = JSON.parse(d);
                //错误信息
                if (dataInfo.status == '30003' || dataInfo.status == '20001' || dataInfo.status == '20000') {
                    layer.closeAll();
                    layer.msg(dataInfo.desc, {icon: 2});
                } else if (dataInfo.status == "0") {//报到
                    layer.closeAll();
                    dealResData(dataInfo.data, patientKey);
                }
            }
        });
    }

    function dealResData(arr, patientKey) {
        arr = arr || [];
        var _queues = [];
        for (var i = 0; i < arr.length; i++) {
            var _deptName = arr[i].deptName;
            _queues = arr[i].queueInfo || [];
            //遍历队列列表
            for (var j = 0; j < _queues.length; j++) {
                //患者姓名
                var _patientName = _queues[j].patientName;
                //注册ID
                var _registerObjKey = _queues[j].registerObjKey;
                //就诊号
                var _patientKey = _queues[j].patientKey;
                var _registerObjName = _queues[j].registerObjName;
                var _queueId = _queues[j].queueId;
                //挂号id
                var _id = _queues[j].id;
                var _isSign = _queues[j].isSign;
                var repeatStatus = "";//重复刷卡
                var normalStatus = "";//正常刷卡
                if (_isSign == 0) {
                    if (patientKeyArr.length > 0) {
                        for (var x = 0; x < patientKeyArr.length; x++) {
                            //根据队列和就诊卡号判断是否重复刷卡
                            if (patientKey == patientKeyArr[x].split("\2")[0] && _queueId == patientKeyArr[x].split("\2")[1]) {
                                patientKeyArr.splice(x, 1);//去除重复信息
                                layer.alert("该患者已经刷卡报到，请勿重复刷卡！", {icon: 2});
                                repeatStatus = 1;
                            } else {
                                normalStatus = 2;
                            }
                        }
                    } else {
                        normalStatus = 2;
                    }
                    var _chkVal = _registerObjKey + "\2" + _registerObjName + "\2" + _id + "\2" + patientKey+ "\2" + _queueId+ "\2" + _isSign;
                    var _patientKeyAndQueueId = patientKey + "\2" + _queueId;
                    patientKeyArr.push(_patientKeyAndQueueId);
                    var _listHtml = "<tr>" +
                        "<td><span style='color:#6DA4EA;'>" + countList + "</span></td>" +
                        "<td class='number'><span>" + _patientKey + "</span></td>" +
                        "<td><span>" + _patientName + "</span></td>" +
                        "<td><span>" + _deptName + "</span></td>" +
                        "<td><button type='button' class='btnDel' onclick='delPatientName(\"" + _patientKeyAndQueueId + "\",\"" + _chkVal + "\",this)'>删除</button></td>" +
                        "</tr>";
                    //如果刷卡同一个队列里有重复号别，数据不更新
                    if (repeatStatus == 1) {
                        _listHtml = "";
                        countList = countList;
                        _chkVal = "";
                    }
                    //如果刷卡同一个队列里没有重复号别，数据更新
                    if (normalStatus == 2) {
                        countList++;
                        if (_chkVal != "") {
                            _queueInfoArr.push(_chkVal);
                        }
                        $("#t_table_plbd_content").append(_listHtml);
                    }
                } else {
                    parent.layer.alert("该患者信息不符合批量报到功能要求，请为其单独报到处理！", {icon: 2});
                }
            }
        }
    }

    //  删除某位患者信息
    function delPatientName(patientKeyAndQueueId, chkVal, that) {
        //  删除患者就诊卡号
        var patientKey = patientKeyAndQueueId.split("\2")[0];
        var queueId = patientKeyAndQueueId.split("\2")[1];
        for (var i = 0; i < patientKeyArr.length; i++) {
            if (patientKeyArr[i].split("\2")[0] == patientKey && patientKeyArr[i].split("\2")[1] == queueId) {
                patientKeyArr.splice(i, 1);
            }
        }
        //删除队列信息
        for (var i = 0; i < _queueInfoArr.length; i++) {
            if (_queueInfoArr[i] == chkVal) {
                _queueInfoArr.splice(i, 1);
            }
        }
        $(that).parent().parent().remove();
    }

    //点击批量报到按钮
    $("#batchBtn").click(function () {
        var _triageId = getDeviceId();
        var _hospiId = getHospitalId();
        for (var i = 0; i < _queueInfoArr.length; i++) {
            var _registerObjKey = _queueInfoArr[i].split("\2")[0];
            var _registerObjName = _queueInfoArr[i].split("\2")[1];
            var _id = _queueInfoArr[i].split("\2")[2];
            var _patientKey = _queueInfoArr[i].split("\2")[3];
            var _queueId = _queueInfoArr[i].split("\2")[4];
            var _isSign = _queueInfoArr[i].split("\2")[5];
            (function () {
                $.ajax({
                    url: fstBdUrl,
                    type: 'post',
                    async: false,
                    data: {
                        hospitalId: _hospiId,   //医院ID
                        triageId: _triageId,   //分诊台ID
                        registerObjKey: _registerObjKey, //队列key
                        registerObjName: _registerObjName,  //队列的名称
                        id: _id   //患者ID
                    },
                    success: function (d) {
                        var jsonObj = JSON.parse(d);
                        if (jsonObj.status == '0') {
                            var signData = JSON.parse(d).data;
                            var trigeType = signData.trigeType; // 1 手动分诊  2 自动分诊
                            if (signData != null) {
                                // 与产品经理徐润泽沟通后，统一分诊进队列
                                (function (signData, _registerObjKey, _patientKey,_queueId,_isSign,_id) {
                                    manualTriage(signData, _registerObjKey, _patientKey,_queueId,_isSign,_id)
                                })(signData, _registerObjKey, _patientKey,_queueId,_isSign,_id)

                                // if(trigeType == 2){
                                //     //报到成功进行分诊
                                //     manualTriage(signData,_registerObjKey,_patientKey);
                                // } else {
                                //     var patientLength =_queueInfoArr[_queueInfoArr.length-1].split("\2")[0];
                                //     if(_registerObjKey == patientLength ){
                                //         layer.msg("批量报到成功！",{icon:1},function () {
                                //             parent&&parent.layer.closeAll()
                                //         })
                                //     }
                                // }
                            }
                        } else {
                            //报到异常的提示信息
                            _patientKeyArr.push(_patientKey + "\2" + jsonObj.desc);
                            var patientLength = _queueInfoArr[_queueInfoArr.length - 1].split("\2")[0];
                            if (_registerObjKey == patientLength) {
                                var msg = "";
                                for (var i = 0; i < _patientKeyArr.length; i++) {
                                    msg += "</br><span style='color:red'>" + _patientKeyArr[i].split("\2")[0] + "</span><span>，" + _patientKeyArr[i].split("\2")[1] + "</span>";
                                }
                                // layer.alert("就诊号:" +msg,{icon: 2});
                                layer.alert("就诊号:" + msg, {
                                    closeBtn: 0,
                                    icon: 2,
                                    zIndex: 19892002,
                                    cancel: function () {
                                    },
                                    yes: function () {
                                        var index = parent.layer.getFrameIndex(window.name);
                                        parent.layer.close(index);
                                    }
                                })
                            }
                        }
                    }
                });
            })()

        }
    });

    //手动分诊
    function manualTriage(signData, registerObjKey, patientKey,queueId,isSign,id) {
        var userId = getLoginUserId();
        var _hospiId = getHospitalId();
        var signId = signData.signId;
        // var signTime = signData.signTime;
        var doctorId = "";
        var doctorName = "";
        var btnType = 3;//预检选项默认3
        $.ajax({
            url: manualTriageUrl,
            type: 'post',
            data: {
                hospitalId: _hospiId,
                editor: userId,
                signIds: signId,
                queueKey: registerObjKey,
                pretestStage: btnType,
                doctorId: doctorId,
                doctorName: doctorName
            },
            success: function (d) {
                var jsonObj = JSON.parse(d);
                if (jsonObj.status == '0') {
                    // layer.alert(jsonObj.desc, {icon: 1});
                    var endPatient = _queueInfoArr[_queueInfoArr.length - 1].split("\2")[0];
                    getTicketInfo(id,queueId,isSign);
                    if (registerObjKey == endPatient) {
                        var msg = "";
                        if (_patientKeyArr.length > 0) {
                            for (var i = 0; i < _patientKeyArr.length; i++) {
                                msg += "</br><span style='color:red'>" + _patientKeyArr[i].split("\2")[0] + "</span><span>，" + _patientKeyArr[i].split("\2")[1] + "</span>";
                            }
                            layer.alert("就诊号:" + msg, {
                                closeBtn: 0,
                                icon: 2,
                                zIndex: 19892002,
                                cancel: function () {

                                },
                                yes: function (index) {
                                    layer.close(index)
                                    layer.msg("批量报到成功！", {icon: 1}, function () {
                                        parent && parent.layer.closeAll()
                                    })
                                }
                            })
                        } else {
                            layer.msg("批量报到成功！", {icon: 1}, function () {
                                parent && parent.layer.closeAll()
                            })
                        }
                    }
                } else {
                    // layer.closeAll();
                    var patientKeyErrArr = [];
                    patientKeyErrArr.push(patientKey + "\2" + jsonObj.desc);
                    var endPatient = _queueInfoArr[_queueInfoArr.length - 1].split("\2")[0];
                    if (registerObjKey == endPatient) {
                        var msgErr = "";
                        for (var i = 0; i < patientKeyErrArr.length; i++) {
                            msgErr += "</br><span style='color:red'>" + patientKeyErrArr[i].split("\2")[0] + "</span><span>，" + patientKeyErrArr[i].split("\2")[1] + "</span>";
                        }
                        layer.alert(msgErr, {icon: 2});
                    }
                }
            }
        });
    }

    //传给上一级页面患者数量，关闭批量报到页面时根据数量提示信息。
    function patientCount(callback) {
        var patientCount = $("#t_table_plbd_content tr").length;
        callback && callback(patientCount)
    }

    function getTicketInfo(id, qid, sign) {
        var _hospiId = getHospitalId();
        $.ajax({
            url: ajaxPrintTicket + '?id=' + id + '&queueId=' + qid + '&isSign=' + sign + '&hospitalId=' + _hospiId,
            type: 'post',
            success: function (d) {
                var res = JSON.parse(d);
                if (res.status == 0) {
                    try{
                        my_cefsharp.PrintInfo(JSON.stringify(res))
                    }catch (e) {

                    }
                }else {
                    layer.msg(res.desc)
                }
            },
            error: function () {

            }
        });
    }

    function dealTicket(res) {
        var arr = res.content || [];
        var fontArr = [18, 24, 36];// 字体大小  对应安卓的 小 中 大
        // 将这部分分开，原因是返回的是数组，顺序不确定
        var title = ''; // 标题
        var frag = '<div>'; // 主体部分
        var tips = ''; // 温馨提示
        var imgCode = '';// 二维码
        var obj = {};
        var rowspacing = res.rowspacing;
        var patientId = '';
        for (var i = 0; i < arr.length; i++) {
            if (arr[i]['isUsed'] == 'true') {
                obj[arr[i]['eKey']] = {
                    title: arr[i]['cKey'],
                    editAttr: JSON.parse(arr[i]['editAttr']),
                    value2: arr[i]['value2'] || '',
                    value: arr[i]['value']
                }
            }
        }
        for (var k in obj) {
            var fonts = parseInt(obj[k].editAttr.font);
            var isweight = obj[k].editAttr.isweight;
            // 标题
            if (k == 'title') {
                title += '<div style="font:' + (fontArr[fonts] || 18) + 'px/' + (fontArr[fonts] || 18) + 'px SimSun;text-align:center;margin:0 0 24px;font-weight:' + (isweight == 1 ? '900' : 'normal') + '">' + obj[k].value + '</div>';
                // 温馨提示
            } else if (k == 'reminder') {
                tips = dealTips(obj[k]['value2'], obj[k]['editAttr']);
                // 二维码
            } else if (k == 'qRcode') {
                imgCode += '<div id="imgCode" class="imgCode" style=";margin:0 0 24px;"></div>';
                patientId = obj[k]['value'];
            } else {
                frag += '<p style="font: ' + (fontArr[fonts] || 18) + 'px/' + (fontArr[fonts] || 18) + 'px SimSun;font-weight:' + (isweight == 1 ? '900' : 'normal') + ';margin:0 0 ' + rowspacing + 'px;">' + obj[k].title + ':' + (obj[k].value || '') + '</p>';
            }
        }
        frag += '</div>';
        $('#print').html(title + imgCode + frag + tips);
        if (patientId != '') {
            $("#imgCode").qrcode({
                width: 90, //宽度
                height: 90, //高度
                text: patientId
            });
            var canvas = $("#imgCode canvas");
            //将canvas转换成png图片，才能被打印机识别打印
            var img = canvas[0].toDataURL("image/png");
            $("#imgCode").html("<img style='width: 90px;height: 90px;display: block;margin: 0 auto' src='" + img + "'>");
        }
        var printData = document.all.item("print").innerHTML;
        var htmlText = "<!DOCTYPE html><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta charset=\"utf-8\" /><title></title></head><body>" +
            "<div id=\"print\" style=\"width: 70mm; height:135mm;left:15px;position:absolute\">" + printData + "</div></body></html>";

        try {
            // 通知csharp做打印
            PrintByCSharp(patientId, htmlText);
        } catch (e) {
            console.warn(e.message)
        }
    }

    function dealTips(str, attr) {
        var fontArr = [18, 24, 36];// 字体大小  对应安卓的 小 中 大
        var fonts = parseInt(attr.font);
        return '<div style="font: ' + (fontArr[fonts] || 18) + 'px/' + (fontArr[fonts] || 18) + 'px SimSun;font-weight:' + (attr.isweight == 1 ? '900' : 'normal') + ';">' + str + '</div>';

    }
</script>
</body>
</html>
